package com.github.dtkavin.bgq.utils

import java.io.IOException

import org.apache.http.client.methods.{CloseableHttpResponse, HttpGet, HttpPost, HttpRequestBase}
import org.apache.http.client.utils.HttpClientUtils
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.slf4j.{Logger, LoggerFactory}

/**
  * @author wangliping
  */
object HttpUtils {
  private val LOG: Logger = LoggerFactory.getLogger(classOf[HttpClientUtils])
  val httpClient = HttpClients.createDefault

  def main(args: Array[String]): Unit = {
    val url = "http://127.0.0.1:8080/event/getEventAndAttrs?pkg=1121"
    //val url = "https://www.baidu.com/"
    val ret = HttpUtils.get(url)
    println(ret)
  }

  def get(url: String): String = {
    val httpGet: HttpGet = new HttpGet(url)
    doHttp(httpGet)
  }

  def post4Json(url: String, jsonBody: String): String = {
    val httpPost = new HttpPost(url)
    httpPost.setHeader("Content-Type", "application/json")
    httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"))
    doHttp(httpPost)
  }

  @throws[IOException]
  private def doHttp(httpRequest: HttpRequestBase): String = {
    var response: CloseableHttpResponse = null
    try {
      response = httpClient.execute(httpRequest)
      if (response.getStatusLine.getStatusCode != 200) {
        LOG.warn("connect to api and response stats is not 200! ")
        null
      } else {
        EntityUtils.toString(response.getEntity, "UTF-8")
      }
    } finally if (response != null) response.close()
  }
}